package com.school.base.action.admin;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.school.base.model.Course;
import com.school.base.model.Lesson;
import com.school.base.service.CourseService;
import com.school.base.service.LessonService;
import com.school.common.base.BaseAction;
import com.school.common.util.FileUtils;
import com.school.common.util.SpringUtils;
import com.school.common.util.SystemConfUtils;

/**
 * @author gaobiao
 * 
 */
public class LessonAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6829235696178269626L;
	private static Logger logger = Logger.getLogger(LessonAction.class);
	private static LessonService service = (LessonService) SpringUtils.getBean("base_lessonService");
	private Lesson lesson;
	private List<Lesson> lessonList;
	private File file;
	private String fileFileName;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public Lesson getLesson() {
		return lesson;
	}

	public void setLesson(Lesson lesson) {
		this.lesson = lesson;
	}

	public List<Lesson> getLessonList() {
		return lessonList;
	}

	public void setLessonList(List<Lesson> lessonList) {
		this.lessonList = lessonList;
	}

	public String list() {
		lessonList = service.getLessonList(lesson, pageBean);
		return SUCCESS;
	}

	public String edit() {
		if (lesson != null && lesson.getId() > 0) {
			lesson = service.getLessonById(lesson.getId());
		}
		return SUCCESS;
	}

	public String editDo() {
		if ("POST".equals(this.getHttpServletRequest().getMethod())) {
			if (lesson != null) {
				if (lesson.getId() > 0) {
					try {
						service.updateLesson(lesson);
						logger.info("update lesson.");
					} catch (Exception e) {
						this.addActionError(e.getMessage());
						return INPUT;
					}
				} else {
					try {
						service.insertLesson(lesson);
						logger.info("insert lesson.");
					} catch (Exception e) {
						this.addActionError(e.getMessage());
						return INPUT;
					}
				}
			} else {
				logger.info("Not save lesson object is null.");
			}
		} else {
			logger.info("Not save lesson:the request method is not 'post'.");
		}
		return SUCCESS;
	}

	public String delete() {
		if (lesson != null && lesson.getId() > 0) {
			service.deleteLesson(lesson.getId());
			logger.info("delete lesson.");
		} else {
			logger.info("Not delete lesson:lesson's id is null.");
		}
		return SUCCESS;
	}

	public String getCourseName(int courseId) {
		CourseService courseService = (CourseService) SpringUtils.getBean("base_courseService");
		Course course = courseService.getCourseById(courseId);
		return course.getClassName();
	}

	public String batchAdd() {
		return SUCCESS;
	}

	public void batchAddDo() throws IOException {
		HttpServletResponse response = this.getHttpServletResponse();
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		JSONObject json = new JSONObject();
		if (lesson != null) {
			HttpServletRequest request = this.getHttpServletRequest();
			int startNum = Integer.parseInt(request.getParameter("startNum"));
			int endNum = Integer.parseInt(request.getParameter("endNum"));
			if (endNum >= startNum) {
				for (int i = startNum; i <= endNum; i++) {
					Lesson l = new Lesson();
					l.setCourseId(lesson.getCourseId());
					l.setDuration(lesson.getDuration());
					l.setName(String.format(lesson.getName(), i));
					try {
						service.insertLesson(l);
					} catch (Exception e) {
						logger.error(e.getMessage());
						json.put("code", "false");
						json.put("msg", e.getMessage());
						break;
					}
				}
				json.put("code", "true");
			} else {
				json.put("code", "false");
				json.put("msg", "开始课时数大于结尾课时数");
			}
		} else {
			json.put("code", "false");
			json.put("msg", "lesson对象为空");
		}
		response.getWriter().print(json);
	}

	public void upload() {
		if (file != null) {
			String ext = fileFileName.substring(fileFileName.lastIndexOf("."));
			String filePath = "\\upload\\lesson\\media\\";
			String fileBaseUrl = SystemConfUtils.getProperty("system.fileUpload.baseUrl");
			String fileDir = this.getServletContext().getRealPath("/") + filePath;
			String fileName = (new Date()).getTime() + ext;
			String fileUrl = fileBaseUrl + filePath.replace("\\", "/") + fileName;
			try {
				FileUtils.saveFile(file, fileDir + fileName);
				HttpServletResponse response = this.getHttpServletResponse();
				response.setContentType("text/html");
				response.setCharacterEncoding("utf-8");
				response.getWriter().print(fileUrl);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
